package prog1.helpers;

import prog1.common.Parameters;
import prog1.common.Utils;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 07/12/13
 *
 * This class encapsulates the digital signature.
 * Serialization / De-serialization is done using parameters class.
 */
public class SignatureProxy {

    private Signature signature;
    private byte[] data;

    public SignatureProxy(String algorithm, String provider)
            throws NoSuchProviderException, NoSuchAlgorithmException {
        signature = Signature.getInstance(algorithm, provider);
    }

    /**
     * Signs using this signature
     * @throws SignatureException
     */
    public void sign() throws SignatureException {
        data = signature.sign();
    }

    /**
     * Verifies previously signed data
     * @return true if verified, false otherwise
     * @throws SignatureException
     */
    public boolean verify() throws SignatureException {
        return signature.verify(data);
    }

    /**
     * Serializes this object to parameters
     * @param parameters target object
     */
    public void serialize(Parameters parameters) {
        parameters.add("SIGNATURE", Arrays.toString(data));
        parameters.add("SIGNATURE_SIZE", String.valueOf(data.length));
    }

    /**
     * De-serializes this object from parameters
     * @param parameters source object
     */
    public void deserialize(Parameters parameters) {
        String signatureStr = parameters.get("SIGNATURE");
        String sizeStr = parameters.get("SIGNATURE_SIZE");
        int size = Integer.parseInt(sizeStr);
        data = Utils.parseByteArray(size, signatureStr);
    }

    /**
     * @return encapsulated signature object
     */
    public Signature getSignature() {
        return signature;
    }
}
